home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 3: Developer Tools / Linux Cubed Series 3 - Developer Tools.iso / utils / file / managers / mc-3.2 / mc-3 / mc-3.2.1 / src / complete.c < prev    next >
Encoding:
C/C++ Source or Header  |  1996-05-17  |  29.9 KB  |  1,061 lines

  1. /* Input line filename/username/hostname/variable/command completion.
  2.    (Let mc type for you...)
  3.    
  4.    Copyright (C) 1995 The Free Software Foundation
  5.    
  6.    Written by: 1995 Jakub Jelinek
  7.    
  8.    This program is free software; you can redistribute it and/or modify
  9.    it under the terms of the GNU General Public License as published by
  10.    the Free Software Foundation; either version 2 of the License, or
  11.    (at your option) any later version.
  12.    
  13.    This program is distributed in the hope that it will be useful,
  14.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  15.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16.    GNU General Public License for more details.
  17.  
  18.    You should have received a copy of the GNU General Public License
  19.    along with this program; if not, write to the Free Software
  20.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  21.  
  22. #include <config.h>
  23. #include "tty.h"
  24. #include <stdio.h>
  25. #include <stdlib.h>
  26. #include <string.h>
  27. #include <malloc.h>
  28. #ifdef HAVE_UNISTD_H
  29. #   include <unistd.h>
  30. #endif
  31.  
  32. /* unistd.h defines _POSIX_VERSION on POSIX.1 systems. */
  33. #if defined(HAVE_DIRENT_H) || defined(_POSIX_VERSION)
  34. #   include <dirent.h>
  35. #   define NLENGTH(dirent) (strlen ((dirent)->d_name))
  36. #else
  37. #   define dirent direct
  38. #   define NLENGTH(dirent) ((dirent)->d_namlen)
  39.  
  40. #   ifdef HAVE_SYS_NDIR_H
  41. #       include <sys/ndir.h>
  42. #   endif /* HAVE_SYS_NDIR_H */
  43.  
  44. #   ifdef HAVE_SYS_DIR_H
  45. #       include <sys/dir.h>
  46. #   endif /* HAVE_SYS_DIR_H */
  47.  
  48. #   ifdef HAVE_NDIR_H
  49. #       include <ndir.h>
  50. #   endif /* HAVE_NDIR_H */
  51. #endif /* not (HAVE_DIRENT_H or _POSIX_VERSION) */
  52. #include <sys/types.h>
  53. #include <sys/stat.h>
  54. #include <pwd.h>
  55.  
  56. #include "global.h"
  57. #include "mad.h"
  58. #include "util.h"
  59. #include "win.h"
  60. #include "color.h"
  61. #include "dlg.h"
  62. #include "widget.h"
  63. #include "dialog.h"
  64. #include "wtools.h"
  65. #include "complete.h"
  66. #include "main.h"
  67. #include "key.h"        /* XCTRL and ALT macros */
  68.  
  69. /* This flag is used in filename_completion_function */
  70. int ignore_filenames = 0;
  71.  
  72. /* This flag is used by command_completion_function */
  73. /* to hint the filename_completion_function */
  74. int look_for_executables = 0;
  75.  
  76. char *filename_completion_function (char *text, int state)
  77. {
  78.     static DIR *directory;
  79.     static char *filename = NULL;
  80.     static char *dirname = NULL;
  81.     static char *users_dirname = NULL;
  82.     static int filename_len;
  83.     int isdir = 1, isexec = 0;
  84.  
  85.     struct dirent *entry = NULL;
  86.  
  87.     /* If we're starting the match process, initialize us a bit. */
  88.     if (!state){
  89.         char *temp;
  90.  
  91.         if (dirname)
  92.             free (dirname);
  93.         if (filename) 
  94.             free (filename);
  95.         if (users_dirname)
  96.             free (users_dirname);
  97.  
  98.         filename = strdup (text);
  99.         if (!*text)
  100.             text = ".";
  101.         dirname = strdup (text);
  102.  
  103.         temp = strrchr (dirname, PATH_SEP);
  104.  
  105.         if (temp){
  106.         strcpy (filename, ++temp);
  107.         *temp = 0;
  108.     }
  109.         else
  110.         strcpy (dirname, ".");
  111.  
  112.         /* We aren't done yet.  We also support the "~user" syntax. */
  113.  
  114.         /* Save the version of the directory that the user typed. */
  115.         users_dirname = strdup (dirname);
  116.         {
  117.         char *temp_dirname;
  118.  
  119.         temp_dirname = tilde_expand (dirname);
  120.         if (!temp_dirname){
  121.         free (dirname);
  122.         free (users_dirname);
  123.         free (filename);
  124.         dirname = users_dirname = filename = NULL;
  125.         return NULL;
  126.         }
  127.         free (dirname);
  128.         dirname = temp_dirname;
  129.         canonicalize_pathname (dirname);
  130.         /* Here we should do something with variable expansion
  131.            and `command`.
  132.            Maybe a dream - UNIMPLEMENTED yet. */
  133.         }
  134.         directory = opendir (dirname);
  135.         filename_len = strlen (filename);
  136.     }
  137.  
  138.     /* Now that we have some state, we can read the directory. */
  139.  
  140.     while (directory && (entry = readdir (directory))){
  141.         /* Special case for no filename.
  142.        All entries except "." and ".." match. */
  143.         if (!filename_len){
  144.         if (!strcmp (entry->d_name, ".") || !strcmp (entry->d_name, ".."))
  145.             continue;
  146.     } else {
  147.         /* Otherwise, if these match up to the length of filename, then
  148.            it may be a match. */
  149.         if ((entry->d_name[0] != filename[0]) ||
  150.             ((NLENGTH (entry)) < filename_len) ||
  151.         strncmp (filename, entry->d_name, filename_len))
  152.             continue;
  153.     }
  154.     isdir = 1; isexec = 0;
  155.     {
  156.         char *tmp = xmalloc (3 + strlen (dirname) + NLENGTH (entry), "Filename completion");
  157.         struct stat tempstat;
  158.         
  159.         strcpy (tmp, dirname);
  160.         strcat (tmp, PATH_SEP_STR);
  161.         strcat (tmp, entry->d_name);
  162.         canonicalize_pathname (tmp);
  163. #ifdef _OS_NT
  164.         if (!stat (tmp, &tempstat)){
  165.         if (tempstat.st_mode & S_IEXEC)
  166.             isexec = 1;
  167.         }
  168. #else
  169.         /* Unix version */
  170.         if (!stat (tmp, &tempstat)){
  171.             uid_t my_uid = getuid ();
  172.             gid_t my_gid = getgid ();
  173.             
  174.             if (!S_ISDIR (tempstat.st_mode)){
  175.                 isdir = 0;
  176.                 if ((!my_uid && (tempstat.st_mode & 0111)) ||
  177.                     (my_uid == tempstat.st_uid && (tempstat.st_mode & 0100)) ||
  178.                     (my_gid == tempstat.st_gid && (tempstat.st_mode & 0010)) ||
  179.                     (tempstat.st_mode & 0001))
  180.                     isexec = 1;
  181.             }
  182.         }
  183. #endif
  184.         free (tmp);
  185.     }
  186.     switch (look_for_executables)
  187.     {
  188.         case 2: if (!isexec)
  189.                     continue;
  190.                 break;
  191.         case 1: if (!isexec && !isdir)
  192.                     continue;
  193.                 break;
  194.     }
  195.     if (ignore_filenames && !isdir)
  196.         continue;
  197.     break;
  198.     }
  199.  
  200.     if (!entry){
  201.         if (directory){
  202.         closedir (directory);
  203.         directory = NULL;
  204.     }
  205.         if (dirname){
  206.         free (dirname);
  207.         dirname = NULL;
  208.     }
  209.         if (filename){
  210.         free (filename);
  211.         filename = NULL;
  212.     }
  213.         if (users_dirname){
  214.         free (users_dirname);
  215.         users_dirname = NULL;
  216.     }
  217.         return NULL;
  218.     } else {
  219.         char *temp;
  220.  
  221.         if (users_dirname && (users_dirname[0] != '.' || users_dirname[1])){
  222.         int dirlen = strlen (users_dirname);
  223.         temp = xmalloc (3 + dirlen + NLENGTH (entry), "Filename completion");
  224.         strcpy (temp, users_dirname);
  225.         /* We need a `/' at the end. */
  226.         if (users_dirname[dirlen - 1] != PATH_SEP){
  227.             temp[dirlen] = PATH_SEP;
  228.             temp[dirlen + 1] = 0;
  229.         }
  230.         strcat (temp, entry->d_name);
  231.     } else {
  232.         temp = xmalloc (2 + NLENGTH (entry), "Filename completion");
  233.         strcpy (temp, entry->d_name);
  234.     }
  235.     if (isdir)
  236.         strcat (temp, PATH_SEP_STR);
  237.         return temp;
  238.     }
  239. }
  240.  
  241. /* We assume here that text[0] == '~' , if you want to call it in another way,
  242.    you have to change the code */
  243. #ifdef _OS_NT
  244. char *username_completion_function (char *text, int state)
  245. {
  246.     return NULL;
  247. }
  248. #else
  249. char *username_completion_function (char *text, int state)
  250. {
  251.     static struct passwd *entry;
  252.     static int userlen;
  253.  
  254.     if (!state){ /* Initialization stuff */
  255.         setpwent ();
  256.         userlen = strlen (text + 1);
  257.     }
  258.     while ((entry = getpwent ()) != NULL){
  259.         /* Null usernames should result in all users as possible completions. */
  260.         if (!userlen)
  261.             break;
  262.         else if (text[1] == entry->pw_name[0] &&
  263.              !strncmp (text + 1, entry->pw_name, userlen))
  264.         break;
  265.     }
  266.  
  267.     if (!entry){
  268.         endpwent ();
  269.         return NULL;
  270.     } else {
  271.         char *temp = xmalloc (3 + strlen (entry->pw_name), "Username completion");
  272.         
  273.         *temp = '~';
  274.         strcpy (temp + 1, entry->pw_name);
  275.         strcat (temp, PATH_SEP_STR);
  276.         return temp;
  277.     }
  278. }
  279.  
  280. extern char **environ;
  281. #endif /* _OS_NT */
  282.  
  283. /* We assume text [0] == '$' and want to have a look at text [1], if it is
  284.    equal to '{', so that we should append '}' at the end */
  285. char *variable_completion_function (char *text, int state)
  286. {
  287.     static char **env_p;
  288.     static int varlen, isbrace;
  289.     char *p = 0;
  290.  
  291.     if (!state){ /* Initialization stuff */
  292.     isbrace = (text [1] == '{');
  293.         varlen = strlen (text + 1 + isbrace);
  294.         env_p = environ;
  295.     }
  296.  
  297.     while (*env_p){
  298.         p = strchr (*env_p, '=');
  299.         if (p && p - *env_p >= varlen && !strncmp (text + 1 + isbrace, *env_p, varlen))
  300.             break;
  301.         env_p++;
  302.     }
  303.  
  304.     if (!*env_p)
  305.         return NULL;
  306.     else {
  307.         char *temp = xmalloc (2 + 2 * isbrace + p - *env_p, "Variable completion");
  308.  
  309.     *temp = '$';
  310.     if (isbrace)
  311.         temp [1] = '{';
  312.         strncpy (temp + 1 + isbrace, *env_p, p - *env_p);
  313.         if (isbrace)
  314.             strcpy (temp + 2 + (p - *env_p), "}");
  315.         else
  316.             temp [1 + p - *env_p] = 0;
  317.         env_p++;
  318.         return temp;
  319.     }
  320. }
  321.  
  322. #define whitespace(c) ((c) == ' ' || (c) == '\t')
  323. #define cr_whitespace(c) (whitespace (c) || (c) == '\n' || (c) == '\r')
  324.  
  325. static char **hosts = NULL;
  326. static char **hosts_p = NULL;
  327. static int hosts_alloclen = 0;
  328. static void fetch_hosts (char *filename)
  329. {
  330.     FILE *file = fopen (filename, "r");
  331.     char *temp, buffer[256], *name;
  332.     register int i, start;
  333.  
  334.     if (!file)
  335.         return;
  336.  
  337.     while ((temp = fgets (buffer, 255, file)) != NULL){
  338.         /* Skip to first character. */
  339.         for (i = 0; buffer[i] && cr_whitespace (buffer[i]); i++);
  340.         /* Ignore comments... */
  341.         if (buffer[i] == '#')
  342.             continue;
  343.         /* Handle $include. */
  344.         if (!strncmp (buffer + i, "$include ", 9)){
  345.         char *includefile = buffer + i + 9;
  346.         char *t;
  347.  
  348.         /* Find start of filename. */
  349.         while (*includefile && whitespace (*includefile))
  350.             includefile++;
  351.         t = includefile;
  352.  
  353.         /* Find end of filename. */
  354.         while (*t && !cr_whitespace (*t))
  355.             t++;
  356.         *t = '\0';
  357.  
  358.         fetch_hosts (includefile);
  359.         continue;
  360.     }
  361.  
  362.         /* Skip IP #s. */
  363.         for (; buffer[i] && !cr_whitespace (buffer[i]); i++);
  364.  
  365.         /* Get the host names separated by white space. */
  366.         while (buffer[i] && buffer[i] != '#'){
  367.         for (; i && cr_whitespace (buffer[i]); i++);
  368.         if (buffer[i] ==  '#')
  369.             continue;
  370.         for (start = i; buffer[i] && !cr_whitespace (buffer[i]); i++);
  371.             if (i - start == 0)
  372.                 continue;
  373.         name = (char *) xmalloc (i - start + 1, "Hostname completion");
  374.         strncpy (name, buffer + start, i - start);
  375.         name [i - start] = 0;
  376.         {
  377.             char **host_p;
  378.             
  379.             if (hosts_p - hosts >= hosts_alloclen){
  380.                 int j = hosts_p - hosts;
  381.             
  382.                 hosts = realloc ((void *)hosts, ((hosts_alloclen += 30) + 1) * sizeof (char *));
  383.                 hosts_p = hosts + j;
  384.             }
  385.             for (host_p = hosts; host_p < hosts_p; host_p++)
  386.                 if (!strcmp (name, *host_p))
  387.                     break; /* We do not want any duplicates */
  388.             if (host_p == hosts_p){
  389.                 *(hosts_p++) = name;
  390.                 *hosts_p = NULL;
  391.             } else
  392.                 free (name);
  393.         }
  394.     }
  395.     }
  396.     fclose (file);
  397. }
  398.  
  399. char *hostname_completion_function (char *text, int state)
  400. {
  401.     static char **host_p;
  402.     static int textstart, textlen;
  403.  
  404.     if (!state){ /* Initialization stuff */
  405.         char *p;
  406.         
  407.         if (hosts != NULL){
  408.             for (host_p = hosts; *host_p; host_p++)
  409.                 free (*host_p);
  410.             free (hosts);
  411.         }
  412.         hosts = (char **) xmalloc (((hosts_alloclen = 30) + 1) * sizeof (char *), "Hostname completion");
  413.         *hosts = NULL;
  414.         hosts_p = hosts;
  415.         fetch_hosts ((p = getenv ("HOSTFILE")) ? p : "/etc/hosts");
  416.         host_p = hosts;
  417.         textstart = (*text == '@') ? 1 : 0;
  418.         textlen = strlen (text + textstart);
  419.     }
  420.     
  421.     while (*host_p){
  422.         if (!textlen)
  423.             break; /* Match all of them */
  424.         else if (!strncmp (text + textstart, *host_p, textlen))
  425.             break;
  426.         host_p++;
  427.     }
  428.     
  429.     if (!*host_p){
  430.         for (host_p = hosts; *host_p; host_p++)
  431.             free (*host_p);
  432.         free (hosts);
  433.         hosts = NULL;
  434.         return NULL;
  435.     } else {
  436.         char *temp = xmalloc (2 + strlen (*host_p), "Hostname completion");
  437.  
  438.         if (textstart)
  439.             *temp = '@';
  440.         strcpy (temp + textstart, *host_p);
  441.         host_p++;
  442.         return temp;
  443.     }
  444. }
  445.  
  446. /* This is the function to call when the word to complete is in a position
  447.    where a command word can be found. It looks around $PATH, looking for
  448.    commands that match. It also scans aliases, function names, and the
  449.    table of shell built-ins. */
  450. char *command_completion_function (char *text, int state)
  451. {
  452.     static int isabsolute;
  453.     static int phase;
  454.     static int text_len;
  455.     static char **words;
  456.     static char *path;
  457.     static char *cur_path;
  458.     static char *cur_word;
  459.     static int init_state;
  460.     static char *bash_reserved [] = { "if", "then", "else", "elif", "fi",
  461.                                       "case", "esac", "for", "select", "while",
  462.                                       "until", "do", "done", "in", "function" , 0};
  463.     static char *bash_builtins [] = { "alias", "bg", "bind", "break", "builtin",
  464.                           "cd", "command", "continue", "declare", 
  465.                           "dirs", "echo", "enable", "eval", "exec",
  466.                           "exit", "export", "fc", "fg", "getopts",
  467.                           "hash", "help", "history", "jobs", "kill",
  468.                           "let", "local", "logout", "popd", "pushd",
  469.                           "pwd", "read", "readonly", "return", "set",
  470.                           "shift", "source", "suspend", "test", 
  471.                           "times", "trap", "type", "typeset",
  472.                           "ulimit", "umask", "unalias", "unset",
  473.                           "wait" , 0};
  474.     char *p, *found;
  475.  
  476.     if (!state){ /* Initialize us a little bit */
  477.     isabsolute = strchr (text, PATH_SEP) != 0;
  478.         look_for_executables = isabsolute ? 1 : 2;
  479.     if (!isabsolute){
  480.         words = bash_reserved;
  481.         phase = 0;
  482.         text_len = strlen (text);
  483.         p = getenv ("PATH");
  484.         if (!p)
  485.             path = NULL;
  486.         else {
  487.             path = xmalloc (strlen (p) + 2, "Command completion");
  488.             strcpy (path, p);
  489.             path [strlen (p) + 1] = 0;
  490.             p = strchr (path, ':');
  491.             while (p){
  492.                 *p = 0;
  493.                 p = strchr (p + 1, ':');
  494.             }
  495.         }
  496.     }
  497.     }
  498.     
  499.     if (isabsolute){
  500.         p = filename_completion_function (text, state);
  501.         if (!p)
  502.             look_for_executables = 0;
  503.         return p;
  504.     }
  505.  
  506.     found = NULL;    
  507.     switch (phase){
  508.         case 0: /* Reserved words */
  509.         while (*words){
  510.             if (!strncmp (*words, text, text_len))
  511.                 return strdup (*(words++));
  512.             words++;
  513.         }
  514.         phase++;
  515.         words = bash_builtins;
  516.     case 1: /* Builtin commands */
  517.         while (*words){
  518.             if (!strncmp (*words, text, text_len))
  519.                 return strdup (*(words++));
  520.             words++;
  521.         }
  522.         phase++;
  523.         if (!path)
  524.             break;
  525.         cur_path = path;
  526.         cur_word = NULL;
  527.     case 2: /* And looking through the $PATH */
  528.         while (!found){
  529.             if (!cur_word){
  530.             char *expanded;
  531.             
  532.                 if (!*cur_path)
  533.                     break;
  534.             expanded = tilde_expand (cur_path);
  535.             if (!expanded){
  536.             free (path);
  537.             path = NULL;
  538.             return NULL;
  539.             }
  540.                 p = canonicalize_pathname (expanded);
  541.                 cur_word = xmalloc (strlen (p) + 2 + text_len, "Command completion");
  542.                 strcpy (cur_word, p);
  543.                 if (cur_word [strlen (cur_word) - 1] != PATH_SEP)
  544.                     strcat (cur_word, PATH_SEP_STR);
  545.                 strcat (cur_word, text);
  546.                 free (p);
  547.                 cur_path = strchr (cur_path, 0) + 1;
  548.                 init_state = state;
  549.             }
  550.             found = filename_completion_function (cur_word, state - init_state);
  551.             if (!found){
  552.                 free (cur_word);
  553.                 cur_word = NULL;
  554.             }
  555.         }
  556.     }
  557.     
  558.     if (!found){
  559.         look_for_executables = 0;
  560.         if (path)
  561.             free (path);
  562.         return NULL;
  563.     }
  564.     if ((p = strrchr (found, PATH_SEP)) != NULL){
  565.         p++;
  566.         p = strdup (p);
  567.         free (found);
  568.         return p;
  569.     }
  570.     return found;
  571.     
  572. }
  573.  
  574. int match_compare (const void *a, const void *b)
  575. {
  576.     return strcmp (*(char **)a, *(char **)b);
  577. }
  578.  
  579. /* Returns an array of char * matches with the longest common denominator
  580.    in the 1st entry. Then a NULL terminated list of different possible
  581.    completions follows.
  582.    You have to supply your own CompletionFunction with the word you
  583.    want to complete as the first argument and an count of previous matches
  584.    as the second. 
  585.    In case no matches were found we return NULL. */
  586. char **completion_matches (char *text, CompletionFunction entry_function)
  587. {
  588.     /* Number of slots in match_list. */
  589.     int match_list_size;
  590.  
  591.     /* The list of matches. */
  592.     char **match_list = (char **) xmalloc (((match_list_size = 30) + 1) * sizeof (char *), "completion match list");
  593.  
  594.     /* Number of matches actually found. */
  595.     int matches = 0;
  596.  
  597.     /* Temporary string binder. */
  598.     char *string;
  599.  
  600.     match_list[1] = NULL;
  601.  
  602.     while ((string = (*entry_function) (text, matches)) != NULL){
  603.         if (matches + 1 == match_list_size)
  604.         match_list = (char **) realloc (match_list, ((match_list_size += 30) + 1) * sizeof (char *));
  605.         match_list[++matches] = string;
  606.         match_list[matches + 1] = NULL;
  607.     }
  608.  
  609.     /* If there were any matches, then look through them finding out the
  610.        lowest common denominator.  That then becomes match_list[0]. */
  611.     if (matches)
  612.     {
  613.         register int i = 1;
  614.         int low = 4096;        /* Count of max-matched characters. */
  615.  
  616.         /* If only one match, just use that. */
  617.         if (matches == 1){
  618.         match_list[0] = match_list[1];
  619.         match_list[1] = (char *)NULL;
  620.         } else {
  621.             int j;
  622.             
  623.         qsort (match_list + 1, matches, sizeof (char *), match_compare);
  624.  
  625.         /* And compare each member of the list with
  626.            the next, finding out where they stop matching. 
  627.            If we find two equal strings, we have to put one away... */
  628.  
  629.         j = i + 1;
  630.         while (j < matches + 1)
  631.         {
  632.         register int c1, c2, si;
  633.  
  634.         for (si = 0;(c1 = match_list [i][si]) && (c2 = match_list [j][si]); si++)
  635.             if (c1 != c2) break;
  636.         
  637.         if (!c1 && !match_list [j][si]){ /* Two equal strings */
  638.             free (match_list [j]);
  639.             j++;
  640.             if (j > matches)
  641.                 break;
  642.         } else
  643.                 if (low > si) low = si;
  644.         if (i + 1 != j) /* So there's some gap */
  645.             match_list [i + 1] = match_list [j];
  646.             i++; j++;
  647.         }
  648.         matches = i;
  649.             match_list [matches + 1] = NULL;
  650.         match_list[0] = xmalloc (low + 1, "Completion matching list");
  651.         strncpy (match_list[0], match_list[1], low);
  652.         match_list[0][low] = 0;
  653.     }
  654.     } else {                /* There were no matches. */
  655.         free (match_list);
  656.         match_list = NULL;
  657.     }
  658.     return match_list;
  659. }
  660.  
  661. int check_is_cd (char *text, int start, int flags)
  662. {
  663.     char *p, *q = text + start;
  664.             
  665.     for (p = text; *p && p < q && (*p == ' ' || *p == '\t'); p++);
  666.     if (((flags & INPUT_COMPLETE_COMMANDS) && 
  667.         !strncmp (p, "cd", 2) && (p [2] == ' ' || p [2] == '\t') && 
  668.         p + 2 < q) ||
  669.         (flags & INPUT_COMPLETE_CD))
  670.         return 1;
  671.     return 0;
  672. }
  673.  
  674. /* Returns an array of matches, or NULL if none. */
  675. char **try_complete (char *text, int *start, int *end, int flags)
  676. {
  677.     int in_command_position = 0, i;
  678.     char *word, c;
  679.     char **matches = NULL;
  680.     char *command_separator_chars = ";|&{(`";
  681.     char *p = NULL, *q = NULL, *r = NULL;
  682.     int is_cd = check_is_cd (text, *start, flags);
  683.  
  684.     ignore_filenames = 0;
  685.     c = text [*end];
  686.     text [*end] = 0;
  687.     word = strdup (text + *start);
  688.     text [*end] = c;
  689.  
  690.     /* Determine if this could be a command word. It is if it appears at
  691.        the start of the line (ignoring preceding whitespace), or if it
  692.        appears after a character that separates commands. And we have to
  693.        be in a INPUT_COMPLETE_COMMANDS flagged Input line. */
  694.     if (!is_cd && (flags & INPUT_COMPLETE_COMMANDS)){
  695.         i = *start - 1;
  696.         while (i > -1 && (text[i] == ' ' || text[i] == '\t'))
  697.             i--;
  698.         if (i < 0)
  699.         in_command_position++;
  700.         else if (strchr (command_separator_chars, text[i])){
  701.             register int this_char, prev_char;
  702.  
  703.             in_command_position++;
  704.             
  705.             if (i){
  706.                 /* Handle the two character tokens `>&', `<&', and `>|'.
  707.                    We are not in a command position after one of these. */
  708.                 this_char = text[i];
  709.                 prev_char = text[i - 1];
  710.  
  711.                 if ((this_char == '&' && (prev_char == '<' || prev_char == '>')) ||
  712.                 (this_char == '|' && prev_char == '>'))
  713.                 in_command_position = 0;
  714.                 else if (i > 0 && text [i-1] == '\\') /* Quoted */
  715.                 in_command_position = 0;
  716.         }
  717.     }
  718.     }
  719.  
  720.     if (flags & INPUT_COMPLETE_COMMANDS)
  721.         p = strrchr (word, '`');
  722.     if (flags & (INPUT_COMPLETE_COMMANDS | INPUT_COMPLETE_VARIABLES))
  723.         q = strrchr (word, '$');
  724.     if (flags & INPUT_COMPLETE_HOSTNAMES)    
  725.         r = strrchr (word, '@');
  726.     if (q && q [1] == '(' && INPUT_COMPLETE_COMMANDS){
  727.         if (q > p)
  728.             p = q + 1;
  729.         q = NULL;
  730.     }
  731.     
  732.     /* Command substitution? */
  733.     if (p > q && p > r){
  734.         matches = completion_matches (p + 1, command_completion_function);
  735.         if (matches)
  736.             *start += p + 1 - word;
  737.     }
  738.  
  739.     /* Variable name? */
  740.     else if  (q > p && q > r){
  741.         matches = completion_matches (q, variable_completion_function);
  742.         if (matches)
  743.             *start += q - word;
  744.     }
  745.  
  746.     /* Starts with '@', then look through the known hostnames for 
  747.        completion first. */
  748.     else if (r > p && r > q){
  749.         matches = completion_matches (r, hostname_completion_function);
  750.         if (matches)
  751.             *start += r - word;
  752.     }
  753.         
  754.     /* Starts with `~' and there is no slash in the word, then
  755.        try completing this word as a username. */
  756.     if (!matches && *word == '~' && (flags & INPUT_COMPLETE_USERNAMES) && !strchr (word, PATH_SEP))
  757.         matches = completion_matches (word, username_completion_function);
  758.  
  759.  
  760.     /* And finally if this word is in a command position, then
  761.        complete over possible command names, including aliases, functions,
  762.        and command names. */
  763.     if (!matches && in_command_position)
  764.         matches = completion_matches (word, command_completion_function);
  765.         
  766.     else if (!matches && (flags & INPUT_COMPLETE_FILENAMES)){
  767.         if (is_cd)
  768.             ignore_filenames = 1;
  769.         matches = completion_matches (word, filename_completion_function);
  770.         ignore_filenames = 0;
  771.         if (!matches && is_cd && *word != PATH_SEP && *word != '~'){
  772.             char *p, *q = text + *start;
  773.             
  774.             for (p = text; *p && p < q && (*p == ' ' || *p == '\t'); p++);
  775.             if (!strncmp (p, "cd", 2))
  776.                 for (p += 2; *p && p < q && (*p == ' ' || *p == '\t'); p++);
  777.             if (p == q){
  778.         char *cdpath = getenv ("CDPATH");
  779.         char c, *s, *r;
  780.  
  781.         if (cdpath == NULL)
  782.             c = 0;
  783.         else
  784.             c = ':';
  785.         while (!matches && c == ':'){
  786.             s = strchr (cdpath, ':');
  787.             if (s == NULL)
  788.                 s = strchr (cdpath, 0);
  789.             c = *s; 
  790.             *s = 0;
  791.             if (*cdpath){
  792.                 if (*(s - 1) == PATH_SEP)
  793.                     r = copy_strings (cdpath, word, NULL);
  794.                 else
  795.                     r = copy_strings (cdpath, PATH_SEP_STR, word, NULL);
  796.                 ignore_filenames = 1;
  797.                     matches = completion_matches (r, filename_completion_function);
  798.                     ignore_filenames = 0;
  799.                     free (r);
  800.             }
  801.             *s = c;
  802.             cdpath = s + 1;
  803.         }
  804.             }
  805.         }
  806.     }
  807.         
  808.     if (word)
  809.         free (word);
  810.  
  811.     return matches;
  812. }
  813.  
  814. void free_completions (WInput *in)
  815. {
  816.     char **p;
  817.     
  818.     if (!in->completions)
  819.         return;
  820.     for (p=in->completions; *p; p++)
  821.         free (*p);
  822.     free (in->completions);
  823.     in->completions = NULL;
  824. }
  825.  
  826. static int query_height, query_width;
  827. static WInput *input;
  828. static int start, end, min_end;
  829.  
  830. static int insert_text (WInput *in, char *text, int len)
  831. {
  832.     len = min (len, strlen (text)) + start - end;
  833.     if (strlen (in->buffer) + len >= in->current_max_len){
  834.     /* Expand the buffer */
  835.         char *narea = realloc(in->buffer, in->current_max_len + len + in->field_len);
  836.     if (narea){
  837.         in->buffer = narea;
  838.         in->current_max_len += len + in->field_len;
  839.     }
  840.     }
  841.     if (strlen (in->buffer)+1 < in->current_max_len){
  842.         if (len > 0){
  843.         int i, l = strlen (&in->buffer [end]);
  844.         for (i = l + 1; i >= 0; i--)
  845.             in->buffer [end + len + i] = in->buffer [end + i];
  846.     } else if (len < 0){
  847.         char *p = in->buffer + end + len, *q = in->buffer + end;
  848.         while (*q)
  849.             *(p++) = *(q++);
  850.         *p = 0;
  851.     }
  852.     strncpy (in->buffer + start, text, len - start + end);
  853.     in->point += len;
  854.     update_input (in);
  855.     end += len;
  856.     }
  857.     return len != 0;
  858. }
  859.  
  860. static int query_callback (Dlg_head * h, int Par, int Msg)
  861. {
  862.     switch (Msg) {
  863.         case DLG_DRAW:
  864.             attrset (COLOR_NORMAL);
  865.         dlg_erase (h);
  866.             draw_box (h, 0, 0, query_height, query_width);
  867.             break;
  868.             
  869.         case DLG_KEY:
  870.         switch (Par) {
  871.         case KEY_LEFT:
  872.         case KEY_RIGHT:
  873.                 h->running = 0;
  874.                 h->ret_value = 0;
  875.                 return 1;
  876.                 
  877.             case 0177:
  878.             case KEY_BACKSPACE:
  879.             case XCTRL('h'):
  880.                 if (end == min_end){
  881.                     h->running = 0;
  882.                     h->ret_value = 0;
  883.                     return 1;
  884.                 } else {
  885.                     WLEntry *e, *e1;
  886.                     
  887.                     e1 = e = ((WListbox *)(h->current->widget))->list;
  888.                     do {
  889.                         if (!strncmp (input->buffer + start, e1->text, end - start - 1)){
  890.                             listbox_select_entry((WListbox *)(h->current->widget), e1);
  891.                             handle_char (input, Par);
  892.                             end--;
  893.                 send_message (h, h->current->widget,
  894.                     WIDGET_DRAW, 0);
  895.                             break;
  896.                         }
  897.                         e1 = e1->next;
  898.                     } while (e != e1);
  899.                 }
  900.                 return 1;
  901.                 
  902.                 default:
  903.                 if (Par > 0xff || !is_printable (Par)){
  904.                     if (is_in_input_map (input, Par) == 2){
  905.                         if (end == min_end)
  906.                             return 1;
  907.                         h->running = 0;
  908.                         h->ret_value = B_USER; /* This means we want to refill the
  909.                                                list box and start again */
  910.                         return 1;
  911.                     } else
  912.                         return 0;
  913.                 } else {
  914.                     WLEntry *e, *e1;
  915.                     int need_redraw = 0;
  916.                     int low = 4096;
  917.                     char *last_text = NULL;
  918.                     
  919.                     e1 = e = ((WListbox *)(h->current->widget))->list;
  920.                     do {
  921.                         if (!strncmp (input->buffer + start, e1->text, end - start)){
  922.                             if (e1->text [end - start] == Par){
  923.                                 if (need_redraw){
  924.                                     register int c1, c2, si;
  925.                                     
  926.                     for (si = end - start + 1; 
  927.                          (c1 = last_text [si]) &&
  928.                          (c2 = e1->text [si]); si++)
  929.                             if (c1 != c2)
  930.                                 break;
  931.                         if (low > si) 
  932.                             low = si;
  933.                     last_text = e1->text;
  934.                     need_redraw = 2;
  935.                                 } else {
  936.                                     need_redraw = 1;
  937.                                     listbox_select_entry((WListbox *)(h->current->widget), e1);
  938.                                     last_text = e1->text;
  939.                                 }
  940.                             }
  941.                         }
  942.                         e1 = e1->next;
  943.                     } while (e != e1);
  944.                     if (need_redraw == 2){
  945.                         insert_text (input, last_text, low);
  946.                         send_message (h, h->current->widget,WIDGET_DRAW,0);
  947.                     } else if (need_redraw == 1){
  948.                         h->running = 0;
  949.                         h->ret_value = B_ENTER;
  950.                     }
  951.                 }
  952.                 return 1;
  953.         }
  954.         break;
  955.     }
  956.     return 0;
  957. }
  958.  
  959. static int querylist_callback (void *data)
  960. {
  961.     return 1;
  962. }
  963.  
  964. #define DO_INSERTION 1
  965. #define DO_QUERY     2
  966. /* Returns 1 if the user would like to see us again */
  967. int complete_engine (WInput *in, int what_to_do)
  968. {
  969.     if (in->completions && in->point != end)
  970.         free_completions (in);
  971.     if (!in->completions){
  972.         end = in->point;
  973.         for (start = end ? end - 1 : 0; start > -1; start--)
  974.             if (strchr (" \t;|<>", in->buffer [start]))
  975.                 break;
  976.         if (start < end)
  977.             start++;
  978.         in->completions = try_complete (in->buffer, &start, &end, in->completion_flags);
  979.     }
  980.     if (in->completions){
  981.         if (what_to_do & DO_INSERTION) {
  982.             if (insert_text (in, in->completions [0], strlen (in->completions [0]))){
  983.                 if (in->completions [1])
  984.                     beep ();
  985.         } else
  986.             beep ();
  987.         }
  988.         if ((what_to_do & DO_QUERY) && in->completions [1]) {
  989.             int maxlen = 0, i, count = 0;
  990.             int x, y, w, h;
  991.             int start_x, start_y;
  992.             char **p, *q;
  993.             Dlg_head *query_dlg;
  994.             WListbox *query_list;
  995.             
  996.             for (p=in->completions + 1; *p; count++, p++)
  997.                 if ((i = strlen (*p)) > maxlen)
  998.                     maxlen = i;
  999.             start_x = in->widget.x;
  1000.             start_y = in->widget.y;
  1001.             if (start_y - 2 >= count) {
  1002.                 y = start_y - 2 - count;
  1003.                 h = 2 + count;
  1004.             } else {
  1005.                 if (start_y >= LINES - start_y - 1) {
  1006.                     y = 0;
  1007.                     h = start_y;
  1008.                 } else {
  1009.                     y = start_y + 1;
  1010.                     h = LINES - start_y - 1;
  1011.                 }
  1012.             }
  1013.             x = start - in->first_shown - 2 + start_x;
  1014.             w = maxlen + 4;
  1015.             if (x + w > COLS)
  1016.                 x = COLS - w;
  1017.             if (x < 0)
  1018.                 x = 0;
  1019.             if (x + w > COLS)
  1020.                 w = COLS;
  1021.             input = in;
  1022.             min_end = end;
  1023.         query_height = h;
  1024.         query_width  = w;
  1025.             query_dlg = create_dlg (y, x, query_height, query_width,
  1026.                     dialog_colors, query_callback,
  1027.                     "[Completion-query]", "complete", DLG_NONE);
  1028.             query_list = listbox_new (1, 1, w - 2, h - 2, 0, querylist_callback);
  1029.             add_widget (query_dlg, query_list);
  1030.             for (p = in->completions + 1; *p; p++)
  1031.                 listbox_add_item (query_list, 0, 0, *p, NULL);
  1032.             run_dlg (query_dlg);
  1033.             q = NULL;
  1034.             if (query_dlg->ret_value == B_ENTER){
  1035.                 listbox_get_current (query_list, &q, NULL);
  1036.                 if (q)
  1037.                     insert_text (in, q, strlen (q));
  1038.             }
  1039.             if (q || end != min_end)
  1040.                 free_completions (in);
  1041.             i = query_dlg->ret_value; /* B_USER if user wants to start over again */
  1042.             destroy_dlg (query_dlg);
  1043.             if (i == B_USER)
  1044.                 return 1;
  1045.         }
  1046.     } else
  1047.         beep ();
  1048.     return 0;
  1049. }
  1050.  
  1051. void complete (WInput *in)
  1052. {
  1053.     if (in->completions)
  1054.         while (complete_engine (in, DO_QUERY));
  1055.     else if (show_all_if_ambiguous){
  1056.         complete_engine (in, DO_INSERTION);
  1057.         while (complete_engine (in, DO_QUERY));
  1058.     } else
  1059.         complete_engine (in, DO_INSERTION);
  1060. }
  1061.